'use strict';
const db = uniCloud.database();
const chatCollection = db.collection('chats');

exports.main = async (event, context) => {
    try {
        const { userId } = event;

        if (!userId) {
            throw new Error('用户未登录');
        }

        // 获取用户最近的对话
        const result = await chatCollection
            .where({
                userId: userId
            })
            .orderBy('updateTime', 'desc')
            .limit(1)
            .get();

        return {
            code: 0,
            message: '获取成功',
            data: result.data[0] || null
        };
    } catch (error) {
        console.error('获取对话失败:', error);
        return {
            code: -1,
            message: error.message || '获取对话失败',
            data: null
        };
    }
}; 